import type { AxiosResponse } from 'axios';
import axios from 'axios';
import { notification } from 'ant-design-vue';
import { globalStore } from '@/store';

const VITE_HTTP_URL_I5XFORYOU = import.meta.env.VITE_HTTP_URL_I5XFORYOU;
console.log(import.meta.env);
axios.defaults.timeout = 30000;

export interface JsonResult {
  id: string;
  status: number;
  result: any;
  message: string;
}

export function getI5xforyouUrl(url: string) {
  return VITE_HTTP_URL_I5XFORYOU + url;
}

export async function postI5xforyou(url: string, data?: object | string) {
  let jsonResult: JsonResult | undefined;
  await axios({
    url,
    method: 'post',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      Authorization: globalStore.state.loginUser.token,
      'Tcsl-Shardingkey': globalStore.state.loginUser.gcId,
    },
    data: data,
  })
    .then(response => {
      jsonResult = responseHandler(response);
    })
    .catch(err => requestFailed(err));
  return jsonResult;
}

export async function getI5xforyou(url: string, data?: object | string) {
  let jsonResult: JsonResult | undefined;
  await axios({
    url,
    method: 'get',
    headers: {
      Authorization: globalStore.state.loginUser.token,
      'Tcsl-Shardingkey': globalStore.state.loginUser.gcId,
    },
    params: data,
  })
    .then(response => {
      jsonResult = responseHandler(response);
    })
    .catch(err => requestFailed(err));
  return jsonResult;
}

function responseHandler(response: AxiosResponse<JsonResult, any>) {
  if (response.data.status < 0) {
    requestFailed(new Error(response.data.message));
    return;
  }
  return response.data;
}

function requestFailed(err: Error) {
  notification.error({
    message: '错误',
    description: err.message || '请求出现错误，请稍后再试',
    duration: 4,
  });
}
